package com.luo.d3s.ext.data.permission.config;

import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import com.luo.d3s.ext.data.permission.interceptor.DataPermissionInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 数据权限配置 - 兼容PageHelper（确保DataPermissionInterceptor拦截器在PageHelper之前执行）
 *
 * @author luohq
 * @date 2023-06-28
 */
@Configuration
@EnableConfigurationProperties({DataPermissionProps.class})
@ConditionalOnClass(PageHelperAutoConfiguration.class)
@AutoConfigureAfter({MybatisAutoConfiguration.class, PageHelperAutoConfiguration.class})
public class DataPermissionPageHelperAutoConfiguration implements InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(DataPermissionPageHelperAutoConfiguration.class);

    private final List<SqlSessionFactory> sqlSessionFactoryList;

    private DataPermissionProps dataPermissionProps;

    public DataPermissionPageHelperAutoConfiguration(DataPermissionProps dataPermissionProps, List<SqlSessionFactory> sqlSessionFactoryList) {
        this.dataPermissionProps = dataPermissionProps;
        this.sqlSessionFactoryList = sqlSessionFactoryList;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("[DATA_PERMISSION] init DataPermissionInterceptor After PageHelper");
        DataPermissionInterceptor interceptor = new DataPermissionInterceptor(this.dataPermissionProps);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            //确保DataPermissionInterceptor拦截器在PageHelper之前执行（放到最后则最先执行）
            configuration.addInterceptor(interceptor);
        }
    }
}